#!/bin/sh

### BEGIN INIT INFO
# Provides:          me2
# Required-Start:    $local_fs $remote_fs $network $named
# Required-Stop:     $local_fs $remote_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: BOTME2 
# Description:       The JSON everywhere bot!
### END INIT INFO

NAME=me2-fleet
DESC="BOTME2"
DATADIR=/var/cache/me2
PIDFILE=/var/run/me2/me2.pid
PID=`cat $PIDFILE` 2>/dev/null

# Include gozerbot defaults if available
if [ -f /etc/default/me2 ] ; then
    . /etc/default/me2
fi

if [ "$RUN" != "yes" ] ; then
    echo "$NAME disabled; edit /etc/default/me2"
    exit 0
fi

if [ -n "$RUNUSER" ] ; then
    RUNUSER=me2
fi

status()
{
	test -n "$PID" && ps auxw | grep -v grep | grep me2-fleet | grep -q -s " $PID " && return 0
        return 1
}

stop()
{
	if status
	then
		kill -TERM $PID
	fi
}

start()
{
	status && exit 1 # already running
        if [ -f "/etc/me2/config/mainconfig" ]		
        then
        	su $RUNUSER -c "$NAME -d $DATADIR $ARGSTRING 2>/dev/null &"
	else
                su $RUNUSER -c "me2-init -d $DATADIR"
        	rm -rf /etc/me2/config
		ln -s /var/cache/me2/config /etc/me2/config
		su $RUNUSER -c "$NAME -d $DATADIR $ARGSTRING 2>/dev/null &"
	fi
	su $RUNUSER -c "$NAME -d $DATADIR -a 2>/dev/null"
}

case "$1" in
start)
	echo -n "Starting $DESC: $NAME "
	start
	case "$?" in
		0) echo "." ; exit 0 ;;
		1) echo " (already running)." ; exit 0 ;;
		*) echo " (failed)." ; exit 1 ;;
	esac
	;;
stop)
	echo -n "Stopping $DESC: $NAME"
	stop
	case "$?" in
		0) echo "." ; exit 0 ;;
		1) echo " (not running)." ; exit 0 ;;
		*) echo " (failed)." ; exit 1 ;;
	esac
	;;
restart|force-reload|reload)
	echo -n "Restarting $DESC: $NAME"
	stop
	start
	;;
status)
	echo -n "Status of $DESC service: "
	status
	case "$?" in
		0) echo "running." ; exit 0 ;;
		1) echo "not running." ; exit 3 ;;
	esac
	;;
*)
	echo "Usage: /etc/init.d/me2 {start|stop|reload|force-reload|restart|status}" >&2
	exit 1
	;;
esac

*t
